'''
Description: Human Robot with AI. TTS module for Human Robot
Copyright (c) 2024 APS
FilePath: /utils_tts.py
version: 
Author: Humanoid Robot Team
Date: 2024-09-13 13:55:01
LastEditors: SY
LastEditTime: 2024-05-23 15:54:51
'''
# utils_tts.py
# Humanoid DYNAMIC 2025-2-27
# 语音合成模块

print('Importing TTS module...')

import os
import appbuilder
from utils_py.utils_api_key import *
import pyaudio
import wave
import time
import sys

tts_ab = appbuilder.TTS()

def tts(TEXT='vertu assistant', tts_wav_path = 'temp/tts.wav'):
    '''
    语音合成TTS，生成wav音频文件
    '''
    inp = appbuilder.Message(content={"text": TEXT})
    out = tts_ab.run(inp, model="paddlespeech-tts", audio_type="wav")
    with open(tts_wav_path, "wb") as f:
        f.write(out.content["audio_binary"])
    # print("TTS语音合成，导出wav音频文件至：{}".format(tts_wav_path))


def play_wav(wav_file='temp/tts.wav'):
    '''
    播放wav文件
    '''
    wf = wave.open(wav_file, 'rb')
 
    # 实例化PyAudio
    p = pyaudio.PyAudio()
 
    # 打开流
    stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                    channels=wf.getnchannels(),
                    rate=wf.getframerate(),
                    output=True)

    chunk_size = 1024
    # 读取数据
    data = wf.readframes(chunk_size)
 
    # 播放音频
    while data != b'':
        stream.write(data)
        data = wf.readframes(chunk_size)
 
    # 停止流，关闭流和PyAudio
    stream.stop_stream()
    stream.close()
    p.terminate()


def tts_play_wav(TEXT='威图机器人助手', tts_wav_path = 'temp/tts.wav'):
    tts(TEXT, tts_wav_path)
    time.sleep(1)
    play_wav(tts_wav_path)
